﻿using System;
using System.Collections.Generic;
using System.IO;
using ConfigManager.Core;

namespace ConfigManager.Console
{
    class ConsoleDriver
    {
        /// <summary>
        /// Console application entry point.
        /// </summary>
        /// <param name="args">The args.</param>
        public static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                    throw new CommandLineArgsException(ResourceCommandLineStrings.NoConfigFileProvided);

                else if (args[0].ToUpper() == "--HELP")
                    System.Console.Out.WriteLine(ResourceCommandLineStrings.Usage);

                else if (args[0].ToUpper() == "--PROPERTIES")
                    PrintProperties();

                else
                {
                    IDictionary<string, string> properties = new Dictionary<string, string>();
                    DefaultProperties.Load(properties);

                    for (int i = 1; i < args.Length; i++)
                    {
                        string key = null;
                        string val = null;
                        if (!Interpreter.TrySplitKeyPair(args[i], ref key, ref val))
                            throw new CommandLineArgsException(ResourceCommandLineStrings.InvalidFormat);

                        properties.Add(key, val);
                    }

                    XmlConfigGenerator gen = new XmlConfigGenerator(properties);

                    string data = null;
                    using (StreamReader fileReader = new StreamReader(args[0]))
                        data = fileReader.ReadToEnd();

                    data = gen.GenerateConfiguration(data);
                    using (StreamWriter fileWriter = new StreamWriter(args[0]))
                        fileWriter.Write(data);
                }

            }
            catch (Exception ex)
            {
                System.Console.Error.WriteLine(ex.Message);
                System.Console.Out.WriteLine(ResourceCommandLineStrings.Usage);
            }
        }



        /// <summary>
        /// Prints the properties.
        /// </summary>
        public static void PrintProperties()
        {
            IDictionary<string, string> properties = new Dictionary<string, string>();
            DefaultProperties.Load(properties);

            foreach (string key in properties.Keys)
                System.Console.Out.WriteLine(key + "=" + properties[key]);
        }
    }
}
